package com.agh.portal.service;

import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.util.UUID;

import javax.servlet.ServletContext;

import org.apache.commons.io.FilenameUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

@Service
public class FileService {

	@Autowired
	ServletContext servletContext;

	public String save(MultipartFile file, String targetDir) throws Exception {
		String webappRoot = servletContext.getRealPath("/");
		byte[] bytes = file.getBytes();
		File userImgDir = new File(webappRoot + targetDir);
		if (!userImgDir.exists()) {
			userImgDir.mkdirs();
		}

		UUID fileId = UUID.randomUUID();
		String serverFileName = fileId + "." + FilenameUtils.getExtension(file.getOriginalFilename());
		File serverFile = new File(userImgDir + File.separator + serverFileName);
		BufferedOutputStream stream = new BufferedOutputStream(new FileOutputStream(serverFile));
		stream.write(bytes);
		stream.close();
		return serverFileName;
	}
}
